<?php
/**
 * Created by PhpStorm.
 * User: wyq
 * Date: 2021/8/16
 * Time: 10:46
 */

include 'application/libraries/RedisCurd.php';

class Login extends Base_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('users_model');
        $this->load->model('logger_model');
        $this->load->service('Activity_service');
        $this->load->service('Jwt_service');
        $this->load->model('Prop_model');
    }

    //登录
    public function login()
    {
        //获取数据
        $post = $this->input->post();
        //查询是否有该用户名
        $data = $this->users_model->findByUsername($post['username']);
        if ($data) {
            if (encrypt($post['password']) == $data['password']) {
                //记录登录日志
                $sqlData = [
                    'ip' => $_SERVER['SERVER_ADDR'],
                    'init_time' => time(),
                    'user_name' => $post['username'],
                    'uid' => $data['id']
                ];
                $data['init_time'] = time();
                //登录日志
                $this->logger_model->userLoginLog($sqlData);
                Logs::info("用户{$post['username']}登陆成功",[],'userLogin');
                //用户首次登录成功送一个骰子、以及概率获得一个魔盒
                $res = $this->Activity_service->addDice($data['id'],'Login');
//                $data['image'] = "http://cakephp.com/" . $data['image'];
                $data['token'] = $this->Jwt_service->getToken($data['id']);
                if ($res){
                    $data['magicBox'] = $res['magicBox'];
                }
                success($data, '登陆成功！');
            } else {
                fail(501, '密码错误！');
            }
        } else {
            fail(500, '没有该用户！');
        }
    }

    //发送邮箱
    public function sendmail()
    {
        $data = $this->input->post();
        $this->form_validation->set_data($data);
        $this->form_validation->set_rules('email', 'email', 'required|valid_email');
        if ($this->form_validation->run() == FALSE) {
            fail('400', '邮箱地址错误!');
        }

        $email = $data['email'];
        //生成随机6位数验证码
        $code = rand_code(6);
        $conn = getRedis();
        $conn->selectDb(0);
        $key = 'emailCode' . $email;
        //上锁，过期时间60s
        $status = $conn->setNx($key, $code);
        $conn->expire($key, 60);
        if (!$status) {
            fail(500, '操作太快啦,验证码还没过期!');
        }
        $Ema = getEmail();
        $title = "用户注册验证码";
        $content = "<h1>邮箱验证码为{$code}</h1>";
        $res = $Ema->sendmail($email, $title, $content);
        $data = [
            'title' => $title,
            'content' => $content,
            'email' => $email,
        ];
        if ($res) {
            Logs::debug($data);
            success($code, 'success');
        }
        Logs::error($data);
        fail($code, "fail");
    }

    //注册
    public function register()
    {
        $data = $this->input->post();
        $rules = [
            [
                'field' => 'username',
                'label' => '用户名',
                'rules' => 'required'
            ],
            [
                'field' => 'password',
                'label' => '密码',
                'rules' => 'required|min_length[3]|max_length[20]'
            ],
            [
                'field' => 'code',
                'label' => '码',
                'rules' => 'required'
            ]
        ];
        if ($data['password'] != $data['password2']) {
            fail(400, '两次密码不同！');
        }
        $this->form_validation->set_data($data);
        $this->form_validation->set_rules($rules);
        if ($this->form_validation->run() == FALSE) {
            $data = $this->form_validation->error_array();
            $data = current($data);
            fail('400', $data);
        }
        $conn = getRedis();
        $conn->selectDb(0);
        $key = 'emailCode' . $data['email'];
        $code = $conn->get($key);
        if (!$code) {
            fail(400, '验证码已过期！');
        }
        if ($code != $data['code']) {
            fail(400, '验证码错误!');
        }
        $data1['password'] = encrypt($data['password']);
        $data1['create_time'] = $data1['update_time'] = time();
        $data1['username'] = $data['username'];
        $data1['email'] = $data['email'];
        $res = $this->Users_model->register($data1);
        if (!$res) {
            fail(400, '注册失败！');
        }
        success($res, '注册成功');
    }

    //三方登录
    public function thirdPartyLogin()
    {

    }
}